﻿using Dt261.db;
using Dt261.jsonmodel;
using Dt261.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Panuon.UI.Silver.Core;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Cache;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Windows.UI.Xaml.Media;

namespace Dt261.ViewModel
{
    class RegisterWindowViewModel : ViewModelBase
    {

        IPendingHandler handler;
        #region 用户名/密码
        private BitmapImage _tupianyanzhengImage;
        private string _Report;
        private string userName = string.Empty;
        private string passWord = string.Empty;
        private string yanzhengma = string.Empty;
        private bool _IsCancel = true;

        private string psw;


        public string Psw { get => psw; set => psw = value; }


        private string psdplaceholder;


        //this.Image2.Source = new BitmapImage(new Uri("http://www.qc110.com/upload/2015-08-06/f6cc7285-bd93-4bb6-9bc1-4310bbdd4966.jpg")); 




        public RegisterWindowViewModel()
        {
#if DEBUG
            userName = "13390015468";
#endif
            //psdplaceholder = "请输入密码";
        }




        public string Psdplaceholder { get => psdplaceholder; set { psdplaceholder = value; RaisePropertyChanged(); } }
        /// <summary>
        /// 数据库访问类型
        /// </summary>
        public string ServerType { get; set; }

        /// <summary>
        /// 皮肤样式
        /// </summary>
        public string SkinName { get; set; }

        /// <summary>
        /// 进度报告
        /// </summary>
        public string Report
        {
            get { return _Report; }
            set { _Report = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }
        public string YanzhengCode
        {
            get { return yanzhengma; }
            set { yanzhengma = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 禁用按钮
        /// </summary>
        public bool IsCancel
        {
            get { return _IsCancel; }
            set { _IsCancel = value; RaisePropertyChanged(); }
        }

        #endregion

        #region 命令(Binding Command)

        private RelayCommand _signCommand;

        public RelayCommand SignCommand
        {
            get
            {
                if (_signCommand == null)
                {
                    _signCommand = new RelayCommand(() => Register());
                }
                return _signCommand;
            }
        }

        private RelayCommand _exitCommand;

        public RelayCommand ExitCommand
        {
            get
            {
                if (_exitCommand == null)
                {
                    _exitCommand = new RelayCommand(() => ApplicationShutdown());
                }
                return _exitCommand;
            }
        }

        private RelayCommand _GetCodeCommand;

        public RelayCommand GetCodeCommand
        {
            get
            {
                if (_GetCodeCommand == null)
                {
                    _GetCodeCommand = new RelayCommand(() => GetCode());
                }
                return _GetCodeCommand;
            }
        }


        private RelayCommand _resetGetCodeCommand;

        public RelayCommand ResetGetCodeCommand
        {
            get
            {
                if (_resetGetCodeCommand == null)
                {
                    _resetGetCodeCommand = new RelayCommand(() => resetGetCode());
                }
                return _resetGetCodeCommand;
            }
        }


        public void resetGetCode()
        {
            //TupianyanzhengImage = null;
            //Uri resourceUri = new Uri(Http.HOST + "tlyht/user/messages/returnCode");
            //TupianyanzhengImage = new BitmapImage(resourceUri, new RequestCachePolicy(RequestCacheLevel.BypassCache));
            //TupianyanzhengImage.CacheOption = BitmapCacheOption.OnLoad;

            BitmapImage bi = new BitmapImage();

            //bi.BeginInit();
            //bi.UriSource = new Uri(Http.HOST + "tlyht/user/messages/returnCode");
            //bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            //// ..Setting other properties...
            //bi.EndInit();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Stream m = Http.SharedHttp().GetAsync(Http.HOST + "tlyht/user/messages/returnCode").Result.Content.ReadAsStreamAsync().Result;
      
                bi.BeginInit();
                bi.StreamSource = m;
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.EndInit();

            }
         

            TupianyanzhengImage = bi;
        }

        public BitmapImage TupianyanzhengImage
        {
            get
            {
                if (_tupianyanzhengImage == null)
                {
                    // Uri resourceUri = new Uri(Http.HOST + "tlyht/user/messages/returnCode");
                    _tupianyanzhengImage = new BitmapImage();

                    //_tupianyanzhengImage.BeginInit();
                    //_tupianyanzhengImage.UriSource = new Uri(Http.HOST + "tlyht/user/messages/returnCode");
                    //_tupianyanzhengImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    //// ..Setting other properties...
                    //_tupianyanzhengImage.EndInit();




                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        Stream m = Http.SharedHttp().GetAsync(Http.HOST + "tlyht/user/messages/returnCode").Result.Content.ReadAsStreamAsync().Result;
                       // m.Save(ms, m.RawFormat);
                        _tupianyanzhengImage.BeginInit();
                        _tupianyanzhengImage.StreamSource = m;
                        _tupianyanzhengImage.CacheOption = BitmapCacheOption.OnLoad;
                        _tupianyanzhengImage.EndInit();
                      
                    }
                    return _tupianyanzhengImage;


                }

                // GC.Collect();
                return _tupianyanzhengImage;
            }
            set
            {
                _tupianyanzhengImage = value;
                RaisePropertyChanged();
            }
        }




        public async void GetCode()
        {
            try
            {
                if (!IsMobilePhone(UserName))
                {
                    this.Report = "请输入正确的电话号码";
                    return;
                }
                if ( string.IsNullOrWhiteSpace(Password))
                {
                    this.Report = "请输入手机号验证码";
                    return;
                }

                this.IsCancel = false;


                this.Report = "正在获取 . . .";

                // Password = "qwerty";            

                var http = Http.SharedHttp();
                //http.Request.Accept = HttpContentTypes.ApplicationJson;
                //http.Request.ContentType = HttpContentTypes.ApplicationXWwwFormUrlEncoded;


                var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("phone", UserName),
                new KeyValuePair<string, string>("Code", Password),
                new KeyValuePair<string, string>("isVerifyPhone",  "true")
            });




                string result = http.GetResponse(content, Http.HOST + "tlyht/user/messages/authcodeTo", "post");




                //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);
                Console.WriteLine(result);

                JObject o = (JObject)JsonConvert.DeserializeObject(result);

                if (null == Http.errorWithJsonObject(o))
                {

                    this.Report = "验证码已发送";
                    // DMSkin.Core.Broadcast.PushBroadcast("LoginOK", UserName);
                    return;
                }
                else
                {
                    this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                }

                // 



                #endregion
            }
            catch (Exception ex)
            {
                this.Report = ex.Message;
            }
            finally
            {
                this.IsCancel = true;
            }
        }

        public  bool IsMobilePhone(string input)
        {

            Regex regex = new Regex("^1[34578]\\d{9}$");
            return regex.IsMatch(input);

        }
        /// <summary>
        /// 登陆系统
        /// </summary>
        public async void Register()
        {
            try
            {
                if(string.IsNullOrWhiteSpace(UserName) )
                {
                    this.Report = "请输入手机号码";
                    return;
                }
                else if (!IsMobilePhone(UserName))
                {
                    this.Report = "请输入正确的电话号码";
                    return;
                }
                else if ( string.IsNullOrWhiteSpace(YanzhengCode))
                {
                    this.Report = "请输入手机验证码";
                    return;
                }


                #region Register

                this.IsCancel = false;


                //handler = PendingBox.Show("正在查找蓝牙设备...", "请稍后", true, Application.Current.MainWindow, new PendingBoxConfigurations()
                //{
                //    LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
                //    ButtonBrush = "#5DBBEC".ToColor().ToBrush(),

                //});
                //handler.Cancel += delegate
                //{

                //    handler.Close();
                //};


                this.Report = "正在验证 . . .";

                // Password = "qwerty";            

                var http = Http.SharedHttp();

                var content = new FormUrlEncodedContent(new[]
         {
                  //  birthday=20021113&gender=1&password=13390015467&phone=13390015467&username=13390015467
                new KeyValuePair<string, string>("phone", UserName),
            
                new KeyValuePair<string, string>("n_rand", YanzhengCode),

                 //new KeyValuePair<string, string>("appEdition", "www.tinglibao.com.cn.pc1.0"),
                 // new KeyValuePair<string, string>("appId", "www.tinglibao.com.cn.pc"),
            });




                string result = http.GetResponse(content, Http.HOST + "tlyht/user/messages/acceptauthcode", "post");




                //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);
                Console.WriteLine(result);

                JObject o = (JObject)JsonConvert.DeserializeObject(result);

                if (null == Http.errorWithJsonObject(o))
                {




                    this.Report = "正在注册 . . .";

                    // Password = "qwerty";            

                    var http2 = Http.SharedHttp();

                    var content2 = new FormUrlEncodedContent(new[]
             {
                  //  birthday=20021113&gender=1&password=13390015467&phone=13390015467&username=13390015467
                new KeyValuePair<string, string>("phone", UserName),
               // new KeyValuePair<string, string>("isVerifyPhone",  "true"),
                new KeyValuePair<string, string>("birthday", "20000103"),
                new KeyValuePair<string, string>("gender", "1"),
                 new KeyValuePair<string, string>("username", UserName),
                new KeyValuePair<string, string>("password", Psw==null?UserName:Psw),
                 new KeyValuePair<string, string>("appEdition", "www.tinglibao.com.cn.pc1.0"),
                  new KeyValuePair<string, string>("appId", "www.tinglibao.com.cn.pc"),
            });


                    string result2 = http2.GetResponse(content2, Http.HOST + "tlyht/user/register", "post");




                    //var response = http.Post(, dict, HttpContentTypes.ApplicationXWwwFormUrlEncoded);
                    Console.WriteLine(result2);

                    JObject o2 = (JObject)JsonConvert.DeserializeObject(result2);

                    if (null == Http.errorWithJsonObject(o2))
                    {

                        UserInfo info = JsonConvert.DeserializeObject<UserInfo>(o2["userInfo"].ToString());
                        //if (UserChecked) SaveLoginInfo();


                        {
                            UserDb db = new UserDb(dbconfig.DatabasePath);
                            User user = db.GetOneUserByUid(info.userId);
                            if (user == null)
                            {
                                user = new User();
                                user.Uid = info.id;
                                user.Name = UserName;
                                //user.IsLogin = true;
                                user.Password = "";
                                db.AddUser(user);
                            }
                            GlobalData.LoginUser = user;
                        }

                        GlobalData.LoginNetUser = info;
                        this.Report = "登陆成功";
                        DMSkin.Core.Broadcast.PushBroadcast("LoginOK", UserName);
                        return;
                    }
                    else
                    {
                        this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                    }
                
                }
                else
                {
                    this.Report = "输入的短信验证码不正确" + ",请重试!";
                }
                #endregion
            }
            catch (Exception ex)
            {
                this.Report = ex.Message;
            }
            finally
            {
                this.IsCancel = true;
            }
        }

        /// <summary>
        /// 关闭系统
        /// </summary>
        public void ApplicationShutdown()
        {
            // Messenger.Default.Send("", "ApplicationShutdown");

        }
    }
}
